import { createRouter, createWebHistory } from 'vue-router';
import store from '../store/index';

const autoLoadRoutes = [];
const reqRouter = require.context('./', true, /\.router\.js$/);
reqRouter.keys().forEach((name) => {
  autoLoadRoutes.push(...reqRouter(name).default);
});

const routes = [
  {
    path: '/Login',
    name: 'Login',
    component: () => import('../views/login/login')
  },
  {
    path: '/',
    name: 'Layout',
    component: () => import('../views/layout/index'),
    children: [
      {
        path: '/',
        name: 'Home',
        component: () => import('../views/home')
      },
      ...autoLoadRoutes
    ]
  }
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
});

router.beforeEach((to, from, next) => {
  if (to.name === 'Login') {
    next();
    return;
  }
  if (store.state.token) {
    next();
  } else {
    next({
      name: 'Login'
    });
  }
});

export default router;
